import { createRouter, createWebHistory } from "vue-router";
// import Home from "@/pages/index.vue";

import { authRouter } from "./auth";
import { dashboardRouter } from "./dashboard";

import { getToken } from "@/utils/fetch";

import { useMenuStore } from "@/stores/modules/menu";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      redirect: "/dashboard/home",
      meta: {
        title: "项目主页"
      }
    },
    authRouter,
    dashboardRouter,
    {
      path: "/:catchAll(.*)",
      name: "not-found",
      component: () => import("@/pages/Common/NotFound/index.vue"),
      meta: {
        title: "404 - 页面未找到"
      }
    }
  ]
});

router.beforeEach((to, from, next) => {
  const userAuthToken = getToken();

  const menuStore = useMenuStore();

  if (to.name !== "login") {
    menuStore.setMenuLoading(true);
  }

  menuStore.setActiveMenu(to.name as string);
  // 如果 userAuthToken 不存在、为 null 或为空字符串，则重定向到登录页面
  if (!userAuthToken || userAuthToken === "") {
    if (to.name !== "login") {
      next({ name: "login" });
    } else {
      next();
    }
  } else {
    // 用户已认证，正常进行路由导航
    next();
  }
  if (to.meta.title) {
    // console.log(import.meta.env);
    document.title = `${import.meta.env.VITE_PROJECT_TITLE} - ${to.meta.title}`;
  }
});

router.afterEach((to) => {
  if (to.name !== "login") {
    const menuStore = useMenuStore();
    menuStore.setMenuLoading(false);
  }
});
export default router;
